using System.Transactions;
using AutoMapper;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructrue.Interfaces;
using BaseData.WriteApi.Application.Command.Roles;
using MediatR;

namespace BaseData.WriteApi.Application.CommandHandler.Roles
{
    /// <summary>
    /// 处理更新角色命令的命令处理器
    /// </summary>
    public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, Apiresult<int>>
    {
        private readonly IBasepository<Role> rolepository;  // 角色仓储接口
        private readonly IBasepository<Permission> permisspository;  // 权限仓储接口
        private readonly IBasepository<RolePermiss> rolePerpository;  // 角色权限仓储接口
        private readonly IMapper mapper;  // 对象映射器
        private readonly ILogger<UpdateRoleCommandHandler> logger;  // 日志记录器

        /// <summary>
        /// 构造函数，注入所需的服务
        /// </summary>
        /// <param name="_rolepository">角色仓储</param>
        /// <param name="_permisspository">权限仓储</param>
        /// <param name="_rolePerpository">角色权限仓储</param>
        /// <param name="_mapper">对象映射器</param>
        /// <param name="_logger">日志记录器</param>
        public UpdateRoleCommandHandler(
            IBasepository<Role> _rolepository,
            IBasepository<Permission> _permisspository,
            IBasepository<RolePermiss> _rolePerpository,
            IMapper _mapper,
            ILogger<UpdateRoleCommandHandler> _logger)
        {
            rolepository = _rolepository;
            permisspository = _permisspository;
            rolePerpository = _rolePerpository;
            mapper = _mapper;
            logger = _logger;
        }

        /// <summary>
        /// 处理更新角色命令
        /// </summary>
        /// <param name="request">更新角色的请求数据</param>
        /// <param name="cancellationToken">取消标记</param>
        /// <returns>返回操作结果</returns>
        public async Task<Apiresult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            // 开启事务处理
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    // 查找要更新的角色
                    var role = await rolepository.GetModel(r => r.RoleId == request.RoleId);
                    if (role == null)
                    {
                        return new Apiresult<int>
                        {
                            Code = ResultCode.查询失败,
                            Message = "角色不存在"
                        };
                    }

                    // 更新角色基本信息
                    role.RoleName = request.RoleName;
                    var roleUpdateResult = await rolepository.EditAsync(role);
                    if (roleUpdateResult <= 0)
                    {
                        tran.Dispose();
                        return new Apiresult<int>
                        {
                            Code = ResultCode.修改失败,
                            Message = "角色信息更新失败"
                        };
                    }

                    // 查找角色当前的权限关联
                    var rolePermission = await rolePerpository.GetModel(rp => rp.RoleId == request.RoleId);
                    if (rolePermission != null)
                    {
                        // 如果权限ID发生变化，更新角色权限关联
                        if (rolePermission.PermissionId != request.PermissionId)
                        {
                            // 验证新权限是否存在
                            var newPermission = await permisspository.GetModel(p => p.PermissionId == request.PermissionId);
                            if (newPermission == null)
                            {
                                tran.Dispose();
                                return new Apiresult<int>
                                {
                                    Code = ResultCode.查询失败,
                                    Message = "权限不存在"
                                };
                            }

                            // 更新角色权限关联
                            rolePermission.PermissionId = request.PermissionId;
                            var permissionUpdateResult = await rolePerpository.EditAsync(rolePermission);
                            if (permissionUpdateResult <= 0)
                            {
                                tran.Dispose();
                                return new Apiresult<int>
                                {
                                    Code = ResultCode.修改失败,
                                    Message = "角色权限更新失败"
                                };
                            }
                        }
                    }
                    else
                    {
                        // 如果没有角色权限关联，创建新的关联
                        var newRolePermission = new RolePermiss
                        {
                            RoleId = request.RoleId,
                            PermissionId = request.PermissionId
                        };
                        var permissionInsertResult = await rolePerpository.InsertAsync(newRolePermission);
                        if (permissionInsertResult <= 0)
                        {
                            tran.Dispose();
                            return new Apiresult<int>
                            {
                                Code = ResultCode.添加失败,
                                Message = "角色权限添加失败"
                            };
                        }
                    }

                    // 提交事务
                    tran.Complete();
                    return new Apiresult<int>
                    {
                        Code = ResultCode.修改成功,
                        Message = "角色信息更新成功"
                    };
                }
                catch (Exception ex)
                {
                    // 发生异常时，回滚事务
                    tran.Dispose();
                    // 记录日志
                    logger.LogError($"UpdateRoleCommandHandler.Handle方法异常：{ex.Message},{ex.StackTrace}");
                    return new Apiresult<int>
                    {
                        Code = ResultCode.修改失败,
                        Message = "系统异常，角色信息更新失败"
                    };
                }
            }
        }
    }
}